import { faceUpload } from 'api/common.js'

/**
 * 图片上传
 * 不压缩上传
 * 上传图片限制大小为10M
 */
const uploadImg = (files, fileType) => {
  return new Promise((resolve, reject) => {
    if (files.size / 1024 > 1024 * 10) {
      resolve({
        success: false,
        message: '图片不能大于10M，请重新上传图片',
        data: null,
      })
    } else {
      let reader = new FileReader()
      reader.readAsDataURL(files)
      reader.onload = (e) => {
        postUpImg(e.target.result, fileType).then((res) => {
          resolve(res)
        })
      }
    }
  })
}

/**
 * 图片压缩上传
 * 图片大于3M进行压缩，压缩后大于5M则图片大小超出最大大小
 */
const compressUploadImg = (files, fileType) => {
  let back = {
    success: false,
    message: '',
    data: null,
  }
  return new Promise(async (resolve, reject) => {
    try {
      if (files.size / 1024 > 3 * 1024) {
        //  大于3M进行压缩
        const quality = 0.5
        const reader = new FileReader()
        reader.readAsDataURL(files)
        reader.onload = (e) => {
          let img = new Image()
          img.src = e.target.result
          img.onload = () => {
            let canvas = document.createElement('canvas')
            let context = canvas.getContext('2d')
            let w = img.width
            let h = img.height
            canvas.setAttribute('width', w)
            canvas.setAttribute('height', h)
            context.drawImage(img, 0, 0, w, h)
            let base64 = canvas.toDataURL('image/jpeg', quality)
            var blobFile = convertBase64UrlToBlob(base64)
            // 压缩后还大于5M，提示图片过大
            if (blobFile.size / 1024 > 1024 * 5) {
              back.message = '图片过大，请重新上传图片'
              resolve(back)
            } else {
              // 上传
              postUpImg(base64, fileType).then((url) => {
                resolve(url)
              })
            }
          }
        }
      } else {
        // 不压缩上传
        uploadImg(files, fileType).then((res) => {
          resolve(res)
        })
      }
    } catch (err) {
      back.message = '图片上传错误'
      resolve(back)
    }
  })
}

// base64 图片转 blob
const convertBase64UrlToBlob = (urlData) => {
  var arr = urlData.split(',')
  var mime = arr[0].match(/:(.*?);/)[1]
  var bstr = atob(arr[1])
  var n = bstr.length
  var u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new Blob([u8arr], { type: mime })
}

/**
 * @description: 文件上传
 * @param {*}
 * file--上传file文件
 * backValue--所需返回参数
 * @return {*}
 */
const postUpImg = (file, fileType) => {
  return new Promise((resolve, reject) => {
    let back = {
      success: false,
      message: '',
      data: null,
    }
    faceUpload({
      base64: file.split(',')[1],
      suffix: 'jpg',
      typeCode: fileType,
    })
      .then((res) => {
        let data = res.data
        if (data.code === '200') {
          back.success = true
          back.data = data.data
        } else {
          back.message = data.message
        }
        resolve(back)
      })
      .catch(() => {
        back.message = '图片上传失败！'
        resolve(back)
      })
  })
}

export { uploadImg, compressUploadImg }
